﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using VCLib.Network.Entity;

namespace PlayListSet.Entity
{
    public class ConnectTcpServer
    {
        public TcpClient TcpClient { get; set; }

        public System.Net.IPEndPoint IPEndPoint { get; set; }

        public Exception Exception { get; set; }
    }

    public class TcpTool
    {
        //
        // 摘要:
        //     TCP连接 超时
        //
        // 参数:
        //   cd:
        //
        //   connectionTimeOut:
        //     连接超时时间
        public static TcpClient Connect(System.Net.IPEndPoint iPEndPoint, int connectionTimeOut)
        {
            TcpClient tcpClient = null;
            Thread thread = new Thread(BeginConnect);
            thread.IsBackground = true;
            ConnectTcpServer connectTcpServer = new ConnectTcpServer
            {
                TcpClient = tcpClient,
                IPEndPoint = iPEndPoint
            };
            thread.Start(connectTcpServer);
            if (thread.Join(connectionTimeOut))
            {
                if (connectTcpServer.Exception != null)
                {
                    throw connectTcpServer.Exception;
                }

                return connectTcpServer.TcpClient;
            }

            tcpClient?.Close();
            thread.Abort();
            if (connectTcpServer.Exception != null)
            {
                throw connectTcpServer.Exception;
            }

            throw new TimeoutException("连接超时");
        }

        //
        // 摘要:
        //     异步连接
        //
        // 参数:
        //   obj:
        public static void BeginConnect(object obj)
        {
            ConnectTcpServer connectTcpServer = (ConnectTcpServer)obj;
            try
            {
                connectTcpServer.TcpClient = new TcpClient();
                connectTcpServer.TcpClient.Connect(connectTcpServer.IPEndPoint);
            }
            catch (Exception ex)
            {
                Exception ex3 = (connectTcpServer.Exception = ex);
            }
        }

    }
}
